<?php
/**
 * Created by zengxianfen on 2020/7/21 18:18.
 */

namespace App\Exception\Handler;


use Hyperf\HttpMessage\Exception\MethodNotAllowedHttpException;
use Hyperf\HttpMessage\Exception\NotFoundHttpException;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Psr\Http\Message\ResponseInterface;
use Throwable;

class ApiExceptionHandler extends ExceptionHandler
{

    /**
     * Handle the exception, and return the specified result.
     */
    public function handle(Throwable $throwable, ResponseInterface $response)
    {
        if ($throwable instanceof NotFoundHttpException || $throwable instanceof MethodNotAllowedHttpException) {
            $data = json_encode(['state'=>0,'msg'=>$throwable->getMessage()],JSON_UNESCAPED_UNICODE);
            $this->stopPropagation();
            return $response->withStatus(200)->withBody(new SwooleStream($data));
        }
        return $response;
    }

    /**
     * Determine if the current exception handler should handle the exception,.
     *
     * @return bool
     *              If return true, then this exception handler will handle the exception,
     *              If return false, then delegate to next handler
     */
    public function isValid(Throwable $throwable): bool
    {
        return true;
    }
}